import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Input } from '@tarojs/components'
import { SDBody } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'
import { GOODS_SEARCH_KEY } from '../../../redux/constants'

import SearchIcon from '../../../images/ic_search_black.png'
import ClearIcon from '../../../images/ic_delete.png'

import './index.less'

type PageState = {
  mainIsLoading: boolean,       // 加载中
  searchHistoryList: any[],     // 搜索历史
  hotSearchList: any[],         // 热搜
  placeHolder: string           // 输入框placeholder
}

type PageOwnProps = {}

interface GoodsSearchPage {
  props: PageProps & PageOwnProps
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class GoodsSearchPage extends Component<PageOwnProps, PageState> {

  constructor () {
    super(...arguments)
    this.state = {
      mainIsLoading: true,
      searchHistoryList: [],
      hotSearchList: [],
      placeHolder: '手镯'
    }
  }

  config: Config = {
    navigationBarTitleText: '商品搜索',
    backgroundColor: '#fff'
  }

  keywords: string = ''

  componentDidMount () {
    this.fetchData()
  }

  render () {
    const { mainIsLoading, searchHistoryList, hotSearchList, placeHolder } = this.state
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className="section-search">
          <View className="search-content">
            <Image className="search-icon" src={SearchIcon}></Image>
            <Input className="search-input" placeholder={placeHolder} confirmType='search' placeholderStyle='color:#999;' onInput={this.onInputValueChange} onConfirm={this.onSearch} />
          </View>
          <View className="search-btn" onClick={this.goBack}>
            <View className="title">取消</View>
          </View>
        </View>
        <View className="main-content">
          {
            hotSearchList.length > 0 ? (
              <View className="section">
                <View className="section-header">
                  <View className="title">热门搜索</View>
                </View>
                <View className="section-list">
                  {
                    hotSearchList.map((item, index) => {
                      return (
                        <View key={index} className="cell-item" onClick={this.execSearch.bind(this, item)}>
                          <View className="title">{item}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            ) : (
              null
            )
          }

          {
            searchHistoryList.length > 0 ? (
              <View className="section">
                <View className="section-header">
                  <View className="title">搜索历史</View>
                  <View className="clear-btn" onClick={this.clearSearchHistoryList}>
                    <Image className="clear-icon" src={ClearIcon}></Image>
                  </View>
                </View>
                <View className="section-list">
                  {
                    searchHistoryList.map((item, index) => {
                      return (
                        <View key={index} className="cell-item" onClick={this.execSearch.bind(this, item)}>
                          <View className="title">{item}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            ) : null
          }
        </View>
      </SDBody>
    )
  }

  fetchData = async () => {
    // 搜索历史
    let searchHistoryList = Taro.getStorageSync(GOODS_SEARCH_KEY) || []
    let hotSearchList: any[] = ['银手镯', '儿童手镯', '情侣手镯', '银饰品']
    let placeHolder = '手镯'
    setTimeout(() => {
      this.setState({
        mainIsLoading: false,
        searchHistoryList: searchHistoryList,
        hotSearchList: hotSearchList,
        placeHolder: placeHolder
      })
    }, 1000)
  }

  goBack = () => {
    Taro.navigateBack()
  }

  onInputValueChange = e => {
    this.keywords = e.detail.value
  }

  onSearch = () => {
    this.execSearch(this.keywords)
  }

  clearSearchHistoryList = () => {
    Taro.removeStorageSync(GOODS_SEARCH_KEY)
    this.setState({
      searchHistoryList: []
    })
  }

  execSearch = (keywords) => {
    let { placeHolder, searchHistoryList = [] } = this.state
    keywords = keywords || placeHolder

    let idx = searchHistoryList.findIndex(item => item == keywords)
    if (idx >= 0) {
      searchHistoryList.splice(idx, 1)
    }

    searchHistoryList.unshift(keywords)
    searchHistoryList = searchHistoryList.slice(0, 10)
    SDUtils.jumpTo('/pages/goods/result/index', {keywords: keywords})
    Taro.setStorageSync(GOODS_SEARCH_KEY, searchHistoryList)
    this.setState({
      searchHistoryList: searchHistoryList
    })
  }

}

export default GoodsSearchPage as ComponentClass<PageOwnProps, PageState>
